package com.example.myapplication.service

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import com.example.myapplication.MainActivity
import com.example.myapplication.R
import com.example.myapplication.api.BackendApiClient
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch

/**
 * Firebase Cloud Messaging 推送服务
 * 接收后端推送的买卖点信号通知
 */
class StockPushMessagingService : FirebaseMessagingService() {

    private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
    private lateinit var apiClient: BackendApiClient
    
    override fun onCreate() {
        super.onCreate()
        apiClient = BackendApiClient(applicationContext)
        createNotificationChannel()
        Log.d(TAG, "🚀 推送服务已启动")
    }

    companion object {
        private const val TAG = "StockPushService"
        private const val CHANNEL_ID = "stock_signals"
        private const val CHANNEL_NAME = "股票交易信号"
        
        // 推送消息类型
        private const val TYPE_BUY_SIGNAL = "buy_signal"
        private const val TYPE_SELL_SIGNAL = "sell_signal"
        private const val TYPE_BATCH_UPDATE = "batch_update"
    }

    /**
     * 收到新的FCM Token时调用
     * 需要将token发送给后端服务器
     */
    override fun onNewToken(token: String) {
        super.onNewToken(token)
        Log.d(TAG, "📱 获得新的FCM Token: $token")
        
        // 异步发送token到后端
        serviceScope.launch {
            try {
                apiClient.registerDeviceToken(token)
                Log.d(TAG, "✅ Token已注册到后端服务器")
            } catch (e: Exception) {
                Log.e(TAG, "❌ Token注册失败: ${e.message}", e)
            }
        }
    }

    /**
     * 收到推送消息时调用
     */
    override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)
        
        Log.d(TAG, "📬 收到推送消息")
        Log.d(TAG, "From: ${message.from}")
        
        // 处理数据载荷
        message.data.let { data ->
            Log.d(TAG, "Data payload: $data")
            
            val type = data["type"] ?: ""
            val stockSymbol = data["stock_symbol"] ?: ""
            val stockName = data["stock_name"] ?: ""
            val signalType = data["signal_type"] ?: ""
            val price = data["price"] ?: ""
            val reason = data["reason"] ?: ""
            
            when (type) {
                TYPE_BUY_SIGNAL -> {
                    showBuySignalNotification(stockSymbol, stockName, price, reason)
                }
                TYPE_SELL_SIGNAL -> {
                    showSellSignalNotification(stockSymbol, stockName, price, reason)
                }
                TYPE_BATCH_UPDATE -> {
                    val buyCount = data["buy_count"] ?: "0"
                    val sellCount = data["sell_count"] ?: "0"
                    showBatchUpdateNotification(buyCount, sellCount)
                }
                else -> {
                    Log.w(TAG, "⚠️ 未知的消息类型: $type")
                }
            }
        }
        
        // 处理通知载荷（如果有）
        message.notification?.let { notification ->
            Log.d(TAG, "Notification title: ${notification.title}")
            Log.d(TAG, "Notification body: ${notification.body}")
            
            showSimpleNotification(
                notification.title ?: "股票提醒",
                notification.body ?: ""
            )
        }
    }

    /**
     * 显示买入信号通知
     */
    private fun showBuySignalNotification(
        symbol: String,
        name: String,
        price: String,
        reason: String
    ) {
        val title = "💰 买入机会：$name ($symbol)"
        val content = "价格：¥$price\n$reason"
        
        val intent = Intent(this, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
            putExtra("stock_symbol", symbol)
            putExtra("action", "open_detail")
        }
        
        val pendingIntent = PendingIntent.getActivity(
            this,
            symbol.hashCode(),
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        
        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle(title)
            .setContentText(content)
            .setStyle(NotificationCompat.BigTextStyle().bigText(content))
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .build()
        
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(symbol.hashCode(), notification)
        
        Log.d(TAG, "✅ 显示买入通知: $symbol")
    }

    /**
     * 显示卖出信号通知
     */
    private fun showSellSignalNotification(
        symbol: String,
        name: String,
        price: String,
        reason: String
    ) {
        val title = "📉 卖出提醒：$name ($symbol)"
        val content = "价格：¥$price\n$reason"
        
        val intent = Intent(this, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
            putExtra("stock_symbol", symbol)
            putExtra("action", "open_detail")
        }
        
        val pendingIntent = PendingIntent.getActivity(
            this,
            symbol.hashCode(),
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        
        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle(title)
            .setContentText(content)
            .setStyle(NotificationCompat.BigTextStyle().bigText(content))
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .build()
        
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(symbol.hashCode(), notification)
        
        Log.d(TAG, "✅ 显示卖出通知: $symbol")
    }

    /**
     * 显示批量更新通知
     */
    private fun showBatchUpdateNotification(buyCount: String, sellCount: String) {
        val title = "📊 股票监控更新"
        val content = "发现 $buyCount 个买入机会，$sellCount 个卖出提醒"
        
        val intent = Intent(this, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
        }
        
        val pendingIntent = PendingIntent.getActivity(
            this,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        
        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle(title)
            .setContentText(content)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .build()
        
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(999, notification)
        
        Log.d(TAG, "✅ 显示批量更新通知")
    }

    /**
     * 显示简单通知
     */
    private fun showSimpleNotification(title: String, body: String) {
        val intent = Intent(this, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
        }
        
        val pendingIntent = PendingIntent.getActivity(
            this,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        
        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle(title)
            .setContentText(body)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .build()
        
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(System.currentTimeMillis().toInt(), notification)
    }

    /**
     * 创建通知渠道（Android 8.0+）
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME,
                NotificationManager.IMPORTANCE_HIGH
            ).apply {
                description = "接收股票买卖点信号推送"
                enableLights(true)
                enableVibration(true)
            }
            
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
            
            Log.d(TAG, "📢 通知渠道已创建")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "🛑 推送服务已停止")
    }
}

